package server

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"gitee.com/johng/gf/g/net/gtcp"
	"gitee.com/johng/gf/g/os/glog"
	"log"
	"time"
)

type P struct {
	X, Y, Z int
	Name    string
}
type Q struct {
	X, Y *int32
	Name string
}

func doWork(data []byte, conn *gtcp.Conn) {
	if len(data) > 0 {
		/*if err := conn.Send(append([]byte("> "), data...)); err != nil {
			fmt.Println(err)
		}*/
		fmt.Println("111111111111")
		var network *bytes.Buffer
		network=bytes.NewBuffer(data)
		dec := gob.NewDecoder(network) // Will read from network.
		var q Q
		err := dec.Decode(&q)
		if err != nil {
			log.Fatal("decode error 1:", err)
		}
		fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)
		err = dec.Decode(&q)
		if err != nil {
			log.Fatal("decode error 2:", err)
		}
		fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)
	}
}

func Send(datas []byte) {
	// Server
	go func() {
		_ = gtcp.NewServer("127.0.0.1:8999", func(conn *gtcp.Conn) {
			defer conn.Close()
			for {
				data, err := conn.Recv(-1)
				if len(data) > 0 {
					//fmt.Println(string(data))
					doWork(data, conn)
				}
				if err != nil {
					break
				}
			}
		}).Run()
	}()

	time.Sleep(time.Second)

	// Client
	conn, err := gtcp.NewConn("127.0.0.1:8999")
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	for i := 0; i < 10000; i++ {
		if err := conn.Send(datas); err != nil {
			glog.Error(err)
		}
		time.Sleep(time.Second)
	}
}
